from twisted.protocols import amp
from pymongo.connection import MongoClient

class MongoDb():
    MONGODB_SERVER = "localhost"
    MONGODB_PORT = 10001
    MONGODB_DB = "books_fs"

    def __init__(self):
        try:
            client = MongoClient(self.MONGODB_SERVER,self.MONGODB_PORT)
            self.db = client[self.MONGODB_DB]
        except Exception as e:
            print "ERROR(MongoDb): %s"%(str(e),)
            traceback.print_exc()

    def insertItem(self,item):
        result = self.db['book_detail'].insert(item)
        mongodb_id = str(result)
        return mongodb_id



class MongoQuery(amp.Command):
    arguments = [('book_name', amp.Unicode()),
                 ('author', amp.Unicode())]
    response = [('result', amp.String())]




class MongoProtocol(amp.AMP):

    def mongoquery(self, book_name,author):
        book_detail = {
            'book_name': book_name,
            'author' : author
        }
        mdb = MongoDb()
        result = mdb.insertItem(book_detail)
        return {'result': result}
    MongoQuery.responder(mongoquery)



def main():
    from twisted.internet import reactor
    from twisted.internet.protocol import Factory
    pf = Factory()
    pf.protocol = MongoProtocol
    reactor.listenTCP(1234, pf)
    print 'started'
    reactor.run()

if __name__ == '__main__':
    main()
